package com.ding.easycontroller.controller;

import com.ding.easycontroller.model.R;
import com.ding.easycontroller.pojo.PluginBrief;
import com.ding.easycontroller.pojo.PluginDetails;
import com.ding.easycontroller.service.PluginService;
import easycontroller.plugin.Plugin;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/_config/plugin")
public class _Plugin {

    @Autowired
    private PluginService pluginService;

    //获取所有插件
    @GetMapping("/all")
    R all(){
        List<Plugin> allPlugins = pluginService.getAllPlugins();
        List<PluginBrief> pluginBriefs = new ArrayList<>();
        for (Plugin plugin : allPlugins) {
            PluginBrief pluginBrief = new PluginBrief();
            BeanUtils.copyProperties(plugin, pluginBrief);
            pluginBriefs.add(pluginBrief);
        }

        List<Plugin> enablePlugins = pluginService.getEnablePlugins();

        out:for (PluginBrief brief : pluginBriefs) {
            for (Plugin plugin : enablePlugins) {
                if (plugin.getName().equals(brief.getName())) {
                    brief.setEnable(true);
                    continue out;
                }
            }
        }

        return R.ok(pluginBriefs);
    }

    @GetMapping("/get")
    R get(String name) {//根据名称获取
        Plugin plugin = pluginService.getByName(name);
        PluginDetails details = new PluginDetails();
        BeanUtils.copyProperties(plugin,details);

        List<Plugin> enablePlugins = pluginService.getEnablePlugins();
        if (enablePlugins.contains(plugin)) {
            details.setEnable(true);
        }

        return R.ok(details);
    }


    //启用一个插件
    @PostMapping("/start")
    R start(String name) {
        pluginService.start(name);
        return R.OK;
    }

    @PostMapping("/restart")
    R restart(String name) {
        pluginService.restart(name);
        return R.OK;
    }

    @PostMapping("/stop")
    R stop(String name){
        pluginService.stop(name);
        return R.OK;
    }


    @PostMapping("/config/{name}")
    R config(@PathVariable String name,@RequestParam  Map<String, String> config) {
        pluginService.config(name, config);
        return R.OK;
    }

}
